import { BizKfExtraProColumnType } from '@/components';
import * as API from '@/services';

import { Divider, message, Space, Typography } from 'antd';
import { KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, toIconComponent } from 'kf-web-library';
import React, { useRef, useState } from 'react';
import QuickMenuForm from './components/QuickForm';
import { useAccess } from '@@/exports';

type Entity = API.Menu_TreeNode;
type EntityPageQueryParams = API.MenuTreeQueryParams;
const entityTypeName = '功能菜单';
const EntityQuickForm = QuickMenuForm;

interface EntityTableListProps {}

/**
 * 菜单列表
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const access = useAccess();
  const [expandedRowKeys, setExpandedRowKeys] = useState<any>([]);

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(params) =>
        API.queryMenuTree(params).then((resp) => {
          /*if (resp.flag) {
          /!**
               * 默认都展开
               *!/
              const expandKeys: string[] = []
              treeWalk(resp.data, (node) => {
                  expandKeys.push(node.id.toString());
              })
              setExpandedRowKeys(expandKeys);
          }*/
          return new Promise((resolve) => resolve(resp as API.RespPageResult<Entity>));
        })
      }
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.id as string, () => {
              API.deleteMenu(record.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
        multi: {
          deleteMultiple: {
            show: true,
            buttonText: '批量删除',
            trigger: (records) => {
              KfModal.batchActionConfirm('删除', records.length, () => {
                API.deleteMenus(records.map((r) => r.id!)).then((res) => {
                  if (res.flag) {
                    message.info('批量删除成功');
                    actionRef.current?.reload();
                  }
                });
              });
            },
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: {
            show: true,
            buttonText: '新建',
            fltRender: () => ({
              title: '测试1',
              content: '测试1内容',
              fltType: 'modal',
              fltModal: {
                width: 800,
              },
            }),
          },
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑${entityTypeName}`,
            content: <EntityQuickForm formType={'modify'} bizId={record.id} />,
          }),
          duplicateModal: (record) => ({
            title: `复制${entityTypeName}`,
            content: <EntityQuickForm formType={'duplicate'} bizId={record.id} />,
          }),
          viewModal: (record) => ({
            title: `查看${entityTypeName}`,
            content: <EntityQuickForm formType={'view'} bizId={record.id} />,
          }),
        },
      }}
      proTable={{
        indentSize: 10,
        search: false,
        pagination: false,
        expandedRowKeys: expandedRowKeys,
        onExpandedRowsChange: setExpandedRowKeys,
      }}
      columns={[
        {
          title: '菜单名称',
          dataIndex: nameof<Entity>((x) => x.name),
          sorter: false,
          hideInSearch: false,
          ellipsis: true,
        },
        {
          title: '唯一标识',
          width: 200,
          dataIndex: nameof<Entity>((x) => x.code),
          sorter: false,
          hideInSearch: false,
          ellipsis: true,
        },
        {
          title: '图标',
          width: 70,
          dataIndex: nameof<Entity>((x) => x.icon),
          sorter: false,
          hideInSearch: false,
          renderText: (text, record) => {
            return toIconComponent(text);
          },
        },
        {
          title: '路径',
          width: 280,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.path),
          sorter: false,
          hideInSearch: false,
          renderText: (text, record) => {
            return record.children && record.children.length > 0 ? '' : text;
          },
        },
        {
          title: '类型',
          width: 100,
          dataIndex: nameof<Entity>((x) => x.type),
          sorter: false,
          hideInSearch: false,
          filters: undefined,
          fieldProps: {
            allowClear: true,
          },
          valueEnum: {
            MENU: { text: '菜单', status: 'Success' },
            BUTTON: { text: '按钮', status: 'Processing' },
          },
        },
        {
          title: '操作',
          fixed: 'right',
          width: 170,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <>
              <Space size={0} split={<Divider type="vertical" />}>
                <a onClick={() => actionRef.current?.openFloating.single?.viewModal(record)}>查看</a>
                {access.hasAnyAuthority('ROLE_ADMIN', 'ROLE_NODE_ADMIN') && (
                  <>
                    <a onClick={() => actionRef.current?.openFloating.single?.modifyModal(record)}>编辑</a>
                    <a onClick={() => actionRef.current?.openFloating.single?.duplicateModal(record)}>
                      <Typography.Text type="warning">复制</Typography.Text>
                    </a>
                    <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                      <Typography.Text type="danger">删除</Typography.Text>
                    </a>
                  </>
                )}
              </Space>
            </>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
